import axios from 'axios'
import { Message } from 'element-ui'
import Vue from 'vue'

const service = axios.create({
  baseURL: 'https://api.apiopen.top/getJoke', // api的base_url
  timeout: 100000 // 请求超时时间
})

// loading框设置局部刷新，且所有请求完成后关闭loading框
let loading

function startLoading() {
  loading = Vue.prototype.$loading({
    lock: true,
    text: 'Loading...',
    spinner: 'el-icon-loading',
    target: document.querySelector('.loading-area')//设置加载动画区域
  })
}

function endLoading() {
  loading.close()
}

//声明一个对象用于存储请求个数
let needLoadingRequestCount = 0

function showFullScreenLoading() {
  if (needLoadingRequestCount === 0) {
    startLoading()
  }
  needLoadingRequestCount++
}

function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
// request拦截器
service.interceptors.request.use(config => {
  showFullScreenLoading()
  config.isForm ?
    config.headers['content-type'] = 'application/x-www-form-urlencoded' :
    config.headers['content-type'] = 'application/json'
  return config
}, error => {
  tryHideFullScreenLoading()
  Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(
  response => {
    tryHideFullScreenLoading()
    return response.data
  },
  error => {
    Message({
      message: '网络错误，请重试!',
      type: 'error'
    })
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @returns Promise
 */
export function post(url, params = {}, isForm = false) {
  return new Promise((resolve, reject) => {
    service({
      url,
      method: 'post',
      data: params,
      isForm
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 * @returns Promise
 */
export function get(url, params = {}, isForm = false) {
  return new Promise((resolve, reject) => {
    service({
      url,
      method: 'get',
      params: params,
      isForm
    }).then(response => {
      resolve(response)
    }).catch(error => {
      reject(error)
    })
  })
}